<?php

/**
 * Description: 查询课堂是否结束
 * User: devforma
 * Date: 15/8/11
 * Time: 16:33
 */
class IsClassOver implements iController
{

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs)
    {

        if (!empty($queryArgs['is_open']) && $queryArgs['is_open'] == 'true') {
            $isOpen = true;
        } else
            $isOpen = false;

        if ($isOpen == false) { //直播课
            if (empty($queryArgs['class_id']) || !filter_var($queryArgs['class_id'], FILTER_VALIDATE_INT)) {
                return genOutput(1000);
            }

            $overTime = $this->classOverTime($queryArgs['class_id'], $isOpen);
        } else {
            if (empty($queryArgs['course_id']) || !filter_var($queryArgs['course_id'], FILTER_VALIDATE_INT)) {
                return genOutput(1000);
            }
            $overTime = $this->classOverTime($queryArgs['course_id'], $isOpen);
        }

        $data = array();
        $data['is_over'] = time() > strtotime($overTime);
        $data['over_time'] = $overTime;

        return genOutput(1, $data);
    }

    private function classOverTime($id, $isOpen = false)
    {

        global $cmsdb;
        if ($isOpen) {
            $sql = 'SELECT cl.over_time, cl.start_time FROM `data_live_class` AS cl, `relationship_live_class_and_course` AS r WHERE cl.id=r.class_id AND r.course_id=:course_id LIMIT 1';

            $data = $cmsdb->getResults($sql, array(
                'course_id' => $id
            ));
        } else {
            $sql = 'SELECT over_time, start_time FROM `data_live_class` WHERE `id`=:class_id';
            $data = $cmsdb->getResults($sql, array(
                'class_id' => $id
            ));
        }

        //如果有老师下课动作，用老师下课的时间作为课堂下课时间，如果没有，用课堂开始时间＋5小时作为课堂下课时间
        if ($data[0] -> over_time != '0000-00-00 00:00:00')
            return $data[0] ->over_time;
        else
            return date('Y-m-d H:i:s', strtotime($data[0] ->start_time) + 5 * 3600);
    }
}